/*
 * @Author: lande 615542329@qq.com
 * @Date: 2023-02-23 11:19:16
 * @LastEditors: lande 615542329@qq.com
 * @LastEditTime: 2023-03-08 17:47:06
 * @FilePath: \GitStorage\Whatsapp_Project\whatsapp_sendmsg.js
 * @Description: send message 
 * @version:1.0.4
 */



try {
    const Diy = require("/sdcard/code/diy_module.js");
    // const Diy = require("../Cloud_Control/diy_module");
} catch (error) {
    console.log("模块加载错误: ", error);
}

const { clickWidget,
    clickWidgetEx,
    widgetBounds,
    findWidget,
    sleepEx,
    sml_move,
    smlMoveUp,
    getLevel,
    clearApp,
    closeApp,
    changeVpn,
    isChangeVpn,
    contactParam,
    ClassRequest,
    countryNameAll,
    PhoneParam

} = Diy;
console.log("开始运行-群发代码");
Diy.setGlobalLog("WhatsApp");
let storage = storages.create("biyun");

try {
    let storageData = storage.get("wsMsg", null);
    console.log("storageData: ", storageData);
    console.log(typeof storageData);
    const WSTaskParam = storageData;
    console.log("WSTaskParam: ", WSTaskParam);
} catch (error) {
    console.log("获取ws推送数据报错: ", error);
}
console.log("WSTaskParam.data.detailId: ", WSTaskParam.data.detailId);
const ClassRequestObj = new ClassRequest("192.168.80.33:80", "ddd5d6c783e943488f71", WSTaskParam.data.detailId);

const Message = (function () {

    function Message() {
        this.instance = null;
        this.status = null;
        this.taskStatus = false;  // 任务成功还是失败
    }
    Message.getInstance = function () {
        if (!this.instance) {
            this.instance = new Message();
        }
        return this.instance;
    }


    /**
    * @description: 启动WhatsApp
    * @return {*}
    */
    Message.prototype.launch = function () {
        $app.launch("com.whatsapp.w4b");
        sleepEx(2000);
        let time1 = new Date().getTime();
        while (!clickWidget(findWidget({ text: "Chats", id: "com.whatsapp.w4b:id/tab", className: "android.widget.TextView" }, "tic"))) {
            clickWidget(findWidget({ text: "OK", id: "android:id/button2", className: "android.widget.Button" }, "tic"));
            clickWidget(findWidget({ id: "com.whatsapp.w4b:id/cancel", className: "android.widget.ImageButton" }, "ic"));
            let time2 = new Date().getTime();
            let time3 = parseInt(time2 - time1) / 1000;
            if (time3 > 15) {
                $app.launch("com.whatsapp.w4b");
                sleepEx(2000);
            } else if (time3 > 30) {
                console.log("失败-启动WhatsApp");
                this.status = "finish";
                this.taskStatus = false;
                break;
            }
            sleep(500);
        }
        this.status = "sendMessage";

    }

    /**
     * @description: 修改手机参数-业务代理
     * @return {*}
     */
    Message.prototype.changePhoneParam = function () {
        this.status = "importConacts";
    }
    /**
     * @description: 导入联系人到通讯录-业务代理
     * @return {*}
     */
    Message.prototype.importConacts = function () {
        this.status = "";
    }

    /**
     * @description: 刷新通讯录到WhatsApp联系人
     * @return {*}
     */
    Message.prototype.refreshConacts = function () {
        clickWidget(findWidget({ text: "KEEP LOCALLY", id: "com.android.contacts:id/left_button", className: "android.widget.Button" }, "tic"));
        clickWidget(findWidget({ text: "Send message", id: "com.whatsapp.w4b:id/fabText", className: "android.widget.TextView" }, "tic"));
        clickWidget(findWidget({ id: "com.whatsapp.w4b:id/fab", className: "android.widget.ImageButton" }, "ic"));
        if (findWidget({ text: "Select contact", className: "android.widget.TextView" }, "tc")) {
            clickWidget(findWidget({ id: "com.whatsapp.w4b:id/menuitem_overflow", className: "android.widget.ImageView" }, "ic"))

        }
        if (clickWidget(findWidget({ text: "Refresh", id: "com.whatsapp.w4b:id/title", className: "android.widget.TextView" }, "tic"))) {
            sleepEx(3000, 5000);
            // className = android.widget.FrameLayout  bounds = (512,88,544,120) 
            this.status = "";
        }
    }

    /**
     * @description: 向指定人发送信息
     * @param {String} contactName 手机号
     * @param {String} msg 发送的消息
     * @param {String} phoneNumber 联系人名字
     * @return {Number} Number  0 是初始状态，表示未开始发送数据，1：发送成功，2：发送失败
     */
    Message.prototype.sendMessage = function (contactName, msg, phoneNumber) {
        let sendStatus = 0;  // 0 是初始状态，表示未开始发送数据，1：发送成功，2：发送失败
        clickWidget(findWidget({ id: "com.whatsapp.w4b:id/fab", className: "android.widget.ImageButton" }, "ic"));
        clickWidget(findWidget({ text: "Send message", id: "com.whatsapp.w4b:id/fabText", className: "android.widget.TextView" }, "tic"));
        if (findWidget({ text: "Select contact", className: "android.widget.TextView" }, "tc")) {
            clickWidget(findWidget({ id: "com.whatsapp.w4b:id/menuitem_search", className: "android.widget.TextView" }, "ic"));
            let numberObj = findWidget({ id: "com.whatsapp.w4b:id/search_src_text", className: "android.widget.EditText" }, "ic");
            if (numberObj) {
                clickWidget(numberObj);
                sleepEx(500);

                numberObj.setText(phoneNumber);
                sleepEx(1500);
            }

        }

        // 搜索出现的内容
        if (findWidget({ text: "No results found for '" + phoneNumber + "'", id: "com.whatsapp.w4b:id/contactpicker_row_name", className: "android.widget.TextView" }, "tic")) {
            console.log("失败-发送消息-手机号未存在");
            sendStatus = 2;
        }
        // 搜索出现的内容
        if (findWidget({ text: "Contacts on WhatsApp", id: "com.whatsapp.w4b:id/title", className: "android.widget.TextView" }, "tic")) {
            clickWidget(findWidget({ text: contactName, id: "com.whatsapp.w4b:id/contactpicker_row_name", className: "android.widget.TextView" }, "tic"));
            sleepEx(1500);
        }
        // fullId = com.whatsapp.w4b:id/entry className = android.widget.EditText text = Message
        let inputBox = findWidget({ text: "Message", id: "com.whatsapp.w4b:id/entry", className: "android.widget.EditText" }, "tic");
        if (inputBox) {
            console.log("找到-消息输入框");
            clickWidget(inputBox);
            inputBox.setText(msg);
            sleepEx(1500);
            console.log("消息-已发送");
            clickWidget(findWidget({ id: "com.whatsapp.w4b:id/send", className: "android.widget.ImageButton" }, "ic"));
            sleepEx(3000);
            let time1 = new Date().getTime();
            while (true) {
                if (findWidget({ text: msg, id: "com.whatsapp.w4b:id/message_text", className: "android.widget.TextView" }, "tic")) {
                    console.log("成功-发送消息");
                    sendStatus = 1;
                    break;
                }
                let time2 = new Date().getTime();
                let time3 = parseInt(time2 - time1) / 1000;
                if (time3 > 30) {
                    console.log("失败-发送消息-超时");
                    sendStatus = 2;
                    break;
                }
                sleepEx(200);
            }

            // 返回主界面
            while (!findWidget({ text: "WhatsApp Business", className: "android.widget.TextView" }, "tc")) {
                back();
                sleepEx(1500);
                if (textContains("This might be because you registered it on another phone").id("android:id/message").className("android.widget.TextView").findOnce()) {
                    sendStatus = 3;
                    return sendStatus;
                }
            }
            return sendStatus;

        }
        return sendStatus;
    }

    /**
     * @description: 向列表联系人逐一发送消息
     * @param {*} taskObj 联系人
     * @return {*}
     */
    Message.prototype.chooseContactsName = function (taskObj) {
        if (typeof taskObj != "object") {
            console.log("taskObj 不是一个对象");
            return;
        }

        // 联系人列表
        const linkmanList = taskObj.data.linkmanList;

        console.log("联系人列表：", linkmanList);
        // 内容列表
        const contentList = taskObj.data.content;
        console.log("内容列表: ", contentList);

        try {
            // contentList.forEach(elementContent => {
            //     console.log("elementContent: ", elementContent);

            linkmanList.forEach(element => {
                console.log("当前发消息的对象: ", element.name, element.phone);
                let result = Message.prototype.sendMessage(element.name, contentList, element.phone);
                if (result == 1) {
                    console.log("任务成功-单条消息的发送");
                    ClassRequestObj.reportSendResult(element.phone, 2)
                        ? console.log("上报成功-单条消息的发送状态") : console.log("上报失败-单条消息的发送状态");

                } else if (result == 3) {
                    this.taskStatus = true;
                    this.status = "finish";
                    console.log("完成-发送消息");
                    return;
                } else {
                    console.log("任务失败-单条消息的发送");
                    ClassRequestObj.reportSendResult(element.phone, 3)
                        ? console.log("上报成功-单条消息的发送状态") : console.log("上报失败-单条消息的发送状态");

                }
                let waitTime = random(parseInt(taskObj.data.intervalMin), parseInt(taskObj.data.intervalMax));
                console.log("等待时间: ", waitTime);
                sleepEx(waitTime);
            });

            // });
        } catch (error) {
            console.log("发消息-报错: ", error);

        }
        this.taskStatus = true;
        this.status = "finish";
        console.log("完成-发送消息");
    }

    return Message;
})().getInstance();


function main() {
    Message.status = "changeVpn";
    let countryCn = countryNameAll(WSTaskParam.data.country, 1);
    console.log("countryCn: ", countryCn);
    while (true) {
        console.log("Message.status: ", Message.status);
        switch (Message.status) {
            case "changeVpn":
                closeApp("com.whatsapp.w4b");
                if (!isChangeVpn(countryCn)) {
                    changeVpn();
                }
                Message.status = "launch";

            case "launch":
                Message.launch();
                break;
            case "sendMessage":
                Message.chooseContactsName(WSTaskParam);
                break;
            case "finish":
                console.log("完成-发送消息任务");

                if (Message.taskStatus) {
                    ClassRequestObj.finishTask("WhatsApp群发任务成功", 2, WSTaskParam.data.detailId)
                        ? console.log("上报-群发任务结果成功") : console.log("上报-群发任务失败");

                } else {
                    ClassRequestObj.finishTask("WhatsApp群发任务失败", 3, WSTaskParam.data.detailId)
                        ? console.log("上报-群发任务结果成功") : console.log("上报-群发任务失败");
                }
                home();
                sleep(2000);
                return;
        }
        sleep(100);
    }

}

main();